package com.cortex.pineapple.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.cortex.pineapple.PineAppleApplication;
import com.cortex.pineapple.PineAppleApplication.OnFetchDataChangedListener;
import com.cortex.pineapple.PineAppleApplication.OnFetchVisitLinkChangedListener;
import com.cortex.pineapple.R;
import com.cortex.pineapple.database.ActionOnDataBase;
import com.cortex.pineapple.database.DataBase.ACTION;
import com.cortex.pineapple.database.Season;
import com.cortex.pineapple.database.SeasonQuerySearch;
import com.cortex.pineapple.database.VisitLink;
import com.cortex.pineapple.fetch.RequestData;
import com.cortex.pineapple.fetch.RequestData.CATEGORY_FILTER_TYPE;
import com.cortex.pineapple.fetch.RequestData.FILTER_TYPE;
import com.cortex.pineapple.fetch.RequestData.FILTER_TYPE.FILTER_VALUE;
import com.cortex.pineapple.fetch.RequestData.SOURCE_TYPE;
import com.cortex.pineapple.fetch.ResponseData;
import com.cortex.pineapple.utilities.HolderData;
import com.cortex.pineapple.view.BrowserView.OnBrowserChangedListener;
import com.cortex.pineapple.view.BrowserView.OnSectionSelectedListener;
import com.cortex.pineapple.view.BrowserView.STATE_BROWSER;
import com.cortex.pineapple.view.CategoriesFiltersView.OnSelectedCategoryFilterListener;
import com.cortex.pineapple.view.CategoriesFiltersView.OnSourcesChangedListener;
import com.cortex.pineapple.view.FiltersView.OnSelectedFilterListener;
import com.cortex.pineapple.view.GalleryImagesView.OnClickUrlListener;
import com.cortex.pineapple.view.GalleryImagesView.OnCloseListener;
import com.cortex.pineapple.view.HistorySearchesView.OnClickExtendedListener;
import com.cortex.pineapple.view.HistorySearchesView.OnClosedHistoryListener;
import com.cortex.pineapple.view.ResultsView.OnFinishedScrollResultsListener;
import com.cortex.pineapple.view.ResultsView.OnSelectedLinkListener;
import com.cortex.pineapple.view.RowSearch.OnRunSearchListener;
import com.cortex.pineapple.view.RowSearch.OnTextChangedListener;
import com.cortext.pineapple.link.ImageLink;
import com.cortext.pineapple.link.Link;

public class HomeView extends RelativeLayout 
	implements SaveState,OnBrowserChangedListener,OnSectionSelectedListener{

	private RelativeLayout searchView;
	private RowSearch rowSearch;
	private ImageView logo;
	private ImageView back;
	private ImageView showHistorySearches;
	private HistorySearchesView historySearchesView;
	private PineAppleApplication app;
	private ResultsView resultsView;
	private CategoriesFiltersView categoriesFiltersView;
	private FiltersView filtersView;
	private ProgressBar waitSearch;
	private LinearLayout containerRowSearch;
	private GalleryImagesView galleryImages;
	private LinearLayout containerResults;
	private boolean isClearResults = true;
	private boolean isHistoryExtendedMode = false;
	private OnLinkSelectedListener onLinkSelectedListener;
	private STATE_HOME_VIEW currentState;
	private SeasonQuerySearch currentSeason;
	private VisitLink currentVisitLink;
	private OnStartNewSeasonListener onStartNewSeasonListener;
	private SOURCE_TYPE browsingSourceType;
	private HolderData holderData = HolderData.getInstance();
	private static final String RESPONSE_DATA = "responseData";
	private static final String STATE_HOME = "state";
	private static final String IMAGE_SHOW = "imageShow";
	private final static int NUMBER_RESULTS_FETCHING = 15;


	public HomeView(Context context) {
		super(context);
		init();
	}
	public HomeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	public HomeView(Context context, AttributeSet attrs,int style) {
		super(context, attrs,style);
		init();
	}
	private void init(){
		LayoutInflater.from(getContext()).inflate(R.layout.view_home, this);
		app = (PineAppleApplication)getContext().getApplicationContext();
		categoriesFiltersView = (CategoriesFiltersView)findViewById(R.id.categoriesFiltersView);
		filtersView = (FiltersView)findViewById(R.id.filtersView);
		rowSearch = (RowSearch)findViewById(R.id.rowSearch);
		logo = (ImageView)findViewById(R.id.logo);
		waitSearch = (ProgressBar)findViewById(R.id.waitSearch);
		containerRowSearch = (LinearLayout)findViewById(R.id.containerRowSearch);
		resultsView = (ResultsView)findViewById(R.id.resultsView);
		containerResults = (LinearLayout)findViewById(R.id.containerResults);
		galleryImages = (GalleryImagesView)findViewById(R.id.galleryImages);
		back = (ImageView)findViewById(R.id.back);
		showHistorySearches = (ImageView)findViewById(R.id.showHistorySearches);
		historySearchesView = (HistorySearchesView)findViewById(R.id.historySearches);
		searchView = (RelativeLayout)findViewById(R.id.searchView);
		rowSearch.setValue("asus");
		rowSearch.registerSpeechQuery();
		currentState = STATE_HOME_VIEW.HOME;
		int orientation = getResources().getConfiguration().orientation;
		if(orientation == Configuration.ORIENTATION_PORTRAIT){
			logo.setImageResource(R.drawable.vertical_logo);
		}
		initListeners();
//		historySearchesView.show();
	}
	private void initListeners(){
		app.setOnStateLinksChanged(new OnFetchDataChangedListener() {

			@Override
			public void dataTimeLoadStarted() {
				waitSearch.setVisibility(View.VISIBLE);
			}

			@Override
			public void dataTimeLoadFinished(ResponseData responseData) {
				waitSearch.setVisibility(View.GONE);
				if(isClearResults){
					resultsView.clear();
				}
				List<Link> iconsToFetch = new ArrayList<Link>();
				resultsView.show(responseData);
				iconsToFetch.addAll(responseData.getNewsLinks());
				app.startFetchingIcons(iconsToFetch);
				app.startFetchingImages(responseData.getNewsLinks());
				moveToState(STATE_HOME_VIEW.RESULTS);
			}

			@Override
			public void dataTimeLoadCancelled(String message) {
				Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
			}
		});
		app.setOnFetchVisitLinkChangedListener(new OnFetchVisitLinkChangedListener() {
			
			@Override
			public void visitLinkTimeLoadStarted() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void visitLinkTimeLoadFinished(VisitLink visitLink) {
				app.getDataBase().doAction(new ActionOnDataBase(ACTION.UPDATE_VISIT_LINK, currentVisitLink));
				if(isHistoryExtendedMode){
					historySearchesView.notifyDataChanged();
				}
			}
			
			@Override
			public void visitLinkTimeLoadCancelled() {
				// TODO Auto-generated method stub
				
			}
		});
		rowSearch.setOnRunSearchListener(new OnRunSearchListener() {
			@Override
			public void search(String query) {
				fetchData(new RequestData(query,NUMBER_RESULTS_FETCHING,0,
						categoriesFiltersView.getSelectedFilter(),
						filtersView.getSelectedFilters()
						,categoriesFiltersView.getSelctedSources()),true);
			}
		});
		categoriesFiltersView.setOnSelectedCategoryFilterListener(new OnSelectedCategoryFilterListener() {

			@Override
			public void selectedFilter(CATEGORY_FILTER_TYPE filterType,List<SOURCE_TYPE> sources) {
				filtersView.clear();
				fetchData(new RequestData(rowSearch.getValue(),NUMBER_RESULTS_FETCHING,0,
						filterType,filtersView.getSelectedFilters(),sources),true);
			}
		});

		categoriesFiltersView.setOnSelectedSourcesListener(new OnSourcesChangedListener() {

			@Override
			public void selectedSource(CATEGORY_FILTER_TYPE filterType, List<SOURCE_TYPE> sources) {
				filtersView.clear();
				if(sources.isEmpty()){
					moveToState(STATE_HOME_VIEW.HOME);
					return;
				}
				fetchData(new RequestData(rowSearch.getValue(),NUMBER_RESULTS_FETCHING,0,
						filterType,filtersView.getSelectedFilters(),sources),true);
			}
		});
		resultsView.setOnFinishedScrollListnener(new OnFinishedScrollResultsListener() {

			@Override
			public void finishedScroll(int totalResults,CATEGORY_FILTER_TYPE filterType , List<SOURCE_TYPE> sources) {
				fetchData(new RequestData(rowSearch.getValue(),NUMBER_RESULTS_FETCHING,
						totalResults,filterType,filtersView.getSelectedFilters(),sources),false);
			}
		});
		filtersView.setOnSelectedFilterListener(new OnSelectedFilterListener() {

			@Override
			public void selectedFilter(HashMap<FILTER_TYPE, FILTER_VALUE> filterChanged,
					HashMap<FILTER_TYPE, FILTER_VALUE> filters) {
				fetchData(new RequestData(rowSearch.getValue(),NUMBER_RESULTS_FETCHING,0,
						categoriesFiltersView.getSelectedFilter(),filters,
						categoriesFiltersView.getSelctedSources()),true);

			}
		});
		resultsView.setOnSelectedLinkListener(new OnSelectedLinkListener() {


			@Override
			public void selectedLink(List<Link> links,Link link) {
				if(link instanceof ImageLink){
					galleryImages.show((List<ImageLink>)(List<?>) links, (ImageLink) link);
					moveToState(STATE_HOME_VIEW.GALLERY);
					return;
				}
				browsingSourceType = link.getSourceType();
				if(onLinkSelectedListener != null){
					onLinkSelectedListener.linkSelected(link);
				}
			}
		});
		galleryImages.setOnClickUrlListener(new OnClickUrlListener() {

			@Override
			public void clickUrl(ImageLink link) {
				browsingSourceType = link.getSourceType();
				if(onLinkSelectedListener != null){
					onLinkSelectedListener.linkSelected(link);
				}
			}
		});
		galleryImages.setOnCloseListener(new OnCloseListener() {

			@Override
			public void closedView() {
				if(!isHistoryExtendedMode){
					back();
				}
			}
		});
		logo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				app.cancelFetchingData();
				app.cancelFetchingIcons();
				app.cancelFetchingImages();
				showHome(true);
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				back();
			}
		});
		showHistorySearches.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(historySearchesView.isShown()){
					historySearchesView.close();
				}
				else{
					moveToState(STATE_HOME_VIEW.HISTORY);
				}
			}
		});
		historySearchesView.setOnClickExtendedListener(new OnClickExtendedListener() {
			
			@Override
			public void onClick() {
				isHistoryExtendedMode = true;
				RelativeLayout.LayoutParams params = (LayoutParams) searchView.getLayoutParams();
				params.addRule(RelativeLayout.LEFT_OF, historySearchesView.getId());
				searchView.setLayoutParams(params);
				
				logo.setImageDrawable(getResources().getDrawable(R.drawable.vertical_logo));
				setEnabled(isHistoryExtendedMode);
			}
		});
		historySearchesView.setOnClosedHistoryListener(new OnClosedHistoryListener() {
			
			@Override
			public void onClosed() {
				back();
			}
		});
		rowSearch.setOnTextChangedListener(new OnTextChangedListener() {
			
			@Override
			public void textChanged(String text) {
				if(isHistoryExtendedMode){
					historySearchesView.show(text);
				}
			}
		});
		filtersView.setOnTouchListener(new OnTouchListener() {
			private int x;
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				x = (int) event.getX();
				LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) filtersView.getLayoutParams();
				switch(event.getAction()){
				case MotionEvent.ACTION_DOWN:
					params.weight = 0;
					params.width = filtersView.getWidth();
					filtersView.setLayoutParams(params);
					return true;
				case MotionEvent.ACTION_MOVE:
					params.width = x;
					filtersView.setLayoutParams(params);	
					break;
				case MotionEvent.ACTION_UP:
				case MotionEvent.ACTION_CANCEL:
					
					break;
				}
				return false;
			}
		});
	}
	private void createNewSeason(){
		// create new season
		currentSeason = new SeasonQuerySearch();
		currentSeason.setName(rowSearch.getValue());
		currentSeason.setQuery(rowSearch.getValue());
		currentSeason.setStartSeason(new Date());
		ActionOnDataBase action = new ActionOnDataBase(ACTION.INSERT_SEASON,currentSeason, null);
		app.getDataBase().doAction(action);
		if(onStartNewSeasonListener != null){
			onStartNewSeasonListener.startedNewSeason(currentSeason);
		}
	}
	public void setOnLinkSelectedListener(OnLinkSelectedListener onLinkSelectedListener) {
		this.onLinkSelectedListener = onLinkSelectedListener;
	}
	public void setOnStartNewSeasonListener(OnStartNewSeasonListener onStartNewSeasonListener) {
		this.onStartNewSeasonListener = onStartNewSeasonListener;
	}
	public STATE_HOME_VIEW getStateHomeView() {
		return currentState;
	}
	public void back() {
		isHistoryExtendedMode = false;
		switch(currentState){
		case GALLERY:
			moveToState(STATE_HOME_VIEW.RESULTS);
			break;
		case HISTORY:
			if(galleryImages.isShown()){
				moveToState(STATE_HOME_VIEW.GALLERY);
			}
			else if(resultsView.isShown()){
				moveToState(STATE_HOME_VIEW.RESULTS);
			}
			else{
				moveToState(STATE_HOME_VIEW.HOME);
			}
			break;
		case HOME:
			moveToState(STATE_HOME_VIEW.HOME);
			break;
		case RESULTS:
			moveToState(STATE_HOME_VIEW.HOME);
			break;
		default:
			break;
		
		}
	}
	@Override
	public void saveState(){
		categoriesFiltersView.saveState();
		ResponseData response = new ResponseData();
		response.setFilters(filtersView.getSelectedFilters());
		response.setFilterType(categoriesFiltersView.getSelectedFilter());
		response.setSourcesType(categoriesFiltersView.getSelctedSources());
		response.setQuery(rowSearch.getValue());
		response.setWebLinks(resultsView.getWebLinks());
		response.setImageLinks(resultsView.getImageLinks());
		response.setVideoLinks(resultsView.getVideoLinks());
		response.setNewsLinks(resultsView.getNewsLinks());
		response.setSuccess(true);
		if(currentState == STATE_HOME_VIEW.HOME){
			response.setSuccess(false);
		}
		if(currentState == STATE_HOME_VIEW.GALLERY){
			ImageLink link = galleryImages.getImageShow();
			holderData.addData(IMAGE_SHOW, link);
		}
		holderData.addData(RESPONSE_DATA,response);
		holderData.addData(STATE_HOME,currentState);

	}
	@Override
	public void restoreState(){
		categoriesFiltersView.restoreState();
		ResponseData response = (ResponseData) holderData.getData(RESPONSE_DATA);
		currentState = (STATE_HOME_VIEW) holderData.getData(STATE_HOME);
		resultsView.show(response);
		rowSearch.setValue(response.getQuery());
		if(currentState == STATE_HOME_VIEW.GALLERY){
			ImageLink link = (ImageLink) holderData.getData(IMAGE_SHOW);
			galleryImages.show((List<ImageLink>)(List<?>) response.getImageLinks(), (ImageLink) link);
		}
		moveToState(currentState);
	}
	private void showHistory(boolean visible){
		historySearchesView.show();
		RelativeLayout.LayoutParams params = (LayoutParams) searchView.getLayoutParams();
		params.addRule(RelativeLayout.LEFT_OF, 0);
		searchView.setLayoutParams(params);
		setEnabled(false);
		back.setVisibility(VISIBLE);
	}
	private void showGallery(boolean visible){
		RelativeLayout.LayoutParams params = (LayoutParams) containerRowSearch.getLayoutParams();
		if(!isHistoryExtendedMode){
			historySearchesView.close();
			logo.setImageDrawable(getResources().getDrawable(R.drawable.horizontal_logo));
			params.width = ViewGroup.LayoutParams.MATCH_PARENT;
			params.addRule(RelativeLayout.LEFT_OF,0);
			setEnabled(true);
		}
		containerResults.setVisibility(VISIBLE);
		back.setVisibility(VISIBLE);
		galleryImages.setVisibility(VISIBLE);
		resultsView.setEnabled(false);
		filtersView.setEnabled(false);
		params.addRule(RelativeLayout.BELOW,categoriesFiltersView.getId());
		
		containerRowSearch.setLayoutParams(params);
	}
	private void showResults(boolean visible){
		RelativeLayout.LayoutParams params = (LayoutParams) containerRowSearch.getLayoutParams();
		if(!isHistoryExtendedMode){
			historySearchesView.close();
			logo.setImageDrawable(getResources().getDrawable(R.drawable.horizontal_logo));
			params.addRule(RelativeLayout.LEFT_OF,0);
		}
		containerResults.setVisibility(VISIBLE);
		back.setVisibility(VISIBLE);
		galleryImages.setVisibility(GONE);
		setEnabled(true);
		params.addRule(RelativeLayout.BELOW,categoriesFiltersView.getId());
		changeFiltersShow();
		
		containerRowSearch.setLayoutParams(params);		
	}
	private void showHome(boolean visible){
		RelativeLayout.LayoutParams params = (LayoutParams) containerRowSearch.getLayoutParams();
		params.addRule(RelativeLayout.BELOW, 0);
		containerResults.setVisibility(GONE);
		galleryImages.setVisibility(GONE);
		back.setVisibility(GONE);
		params.addRule(RelativeLayout.CENTER_IN_PARENT,this.getId());
		if(!isHistoryExtendedMode){
			historySearchesView.close();
			logo.setImageDrawable(getResources().getDrawable(R.drawable.horizontal_logo));
			params.addRule(RelativeLayout.LEFT_OF,0);
		}
		setEnabled(true);
		containerRowSearch.setLayoutParams(params);

	}
	private void moveToState(STATE_HOME_VIEW state){
		switch(state){
		case GALLERY:
			showGallery(true);
			break;
		case RESULTS:
			showResults(true);
			break;
		case HISTORY:
			showHistory(true);
			break;
		case HOME:
		default:
			showHome(true);
			break;

		}
		currentState = state;
	}

	private void changeFiltersShow(){
		if(!isClearResults){
			return;
		}
		int visible = View.VISIBLE;
		switch(categoriesFiltersView.getSelectedFilter()){
		case COMPOSITE:
			visible = View.GONE;
			break;
		case IMAGES:
			filtersView.setVisibleImageType(true);
			filtersView.setVisibleImageSize(true);
			filtersView.setVisibleImageColor(true);
			filtersView.setVisibleImageFace(true);

			filtersView.setVisibleNewsTime(false);
			filtersView.setVisibleNewsCategory(false);
			filtersView.setVisibleVideoLength(false);
			filtersView.setVisibleVideoResolution(false);
			filtersView.setVisibleFilesType(false);
			break;
		case NEWS:
			filtersView.setVisibleNewsTime(true);
			filtersView.setVisibleNewsCategory(true);

			filtersView.setVisibleImageType(false);
			filtersView.setVisibleImageSize(false);
			filtersView.setVisibleImageColor(false);
			filtersView.setVisibleImageFace(false);
			filtersView.setVisibleVideoLength(false);
			filtersView.setVisibleVideoResolution(false);
			filtersView.setVisibleFilesType(false);
			break;
		case VIDEO:
			filtersView.setVisibleVideoLength(true);
			filtersView.setVisibleVideoResolution(true);

			filtersView.setVisibleImageType(false);
			filtersView.setVisibleImageSize(false);
			filtersView.setVisibleImageColor(false);
			filtersView.setVisibleImageFace(false);
			filtersView.setVisibleNewsTime(false);
			filtersView.setVisibleNewsCategory(false);
			filtersView.setVisibleFilesType(false);
			break;
		case WEB:
			filtersView.setVisibleFilesType(true);

			filtersView.setVisibleImageType(false);
			filtersView.setVisibleImageSize(false);
			filtersView.setVisibleImageColor(false);
			filtersView.setVisibleImageFace(false);
			filtersView.setVisibleNewsTime(false);
			filtersView.setVisibleNewsCategory(false);
			filtersView.setVisibleVideoLength(false);
			filtersView.setVisibleVideoResolution(false);
			break;
		default:
			break;

		}
		filtersView.setVisibility(visible);
	}
	public void fetchData(String query){
		rowSearch.setValue(query);
		fetchData(new RequestData(query,NUMBER_RESULTS_FETCHING,0,
				categoriesFiltersView.getSelectedFilter(),
				filtersView.getSelectedFilters()
				,categoriesFiltersView.getSelctedSources()),true);
	}
	private void fetchData(RequestData requestData,boolean isClearResults){
		app.cancelFetchingIcons();
		app.cancelFetchingImages();
		if(!app.isInternetConnection()){
			Toast.makeText(getContext(), getResources().getString(R.string.no_internet), Toast.LENGTH_LONG).show();
		}
		if(!requestData.getQuery().isEmpty()){
			app.startFetchingData(requestData);
			this.isClearResults = isClearResults;
			if(currentSeason != null && currentSeason.getVisitLinks().isEmpty()){
				ActionOnDataBase action = new ActionOnDataBase(ACTION.DELETE_SEASON,currentSeason, null);
				app.getDataBase().doAction(action);
			}
			if(currentSeason == null || !currentSeason.getQuery().equals(requestData.getQuery())){
				createNewSeason();
			}
			return;
		}

		Toast.makeText(getContext(), getResources().getString(R.string.writeSomethingHere), Toast.LENGTH_LONG).show();
	}

	public interface OnLinkSelectedListener{
		void linkSelected(Link link);
	}
	public interface OnStartNewSeasonListener{
		void startedNewSeason(Season season);
	}
	public enum STATE_HOME_VIEW{
		HOME,
		RESULTS,
		GALLERY,
		HISTORY
	}
	@Override
	public void stateChanged(STATE_BROWSER state, String url,Bitmap favicon) {
		
		if(state == STATE_BROWSER.PAGE_FINIHED){
			currentVisitLink = new VisitLink();
			url = url.replace(getResources().getString(R.string.http), "");
			currentVisitLink.setUrl(url);
			currentVisitLink.setSource(browsingSourceType);
			currentVisitLink.setIdSeason(currentSeason.getId());
			currentVisitLink.setStartVisit(new Date());
			currentVisitLink.setFavicon(favicon);
			if(!currentSeason.getVisitLinks().contains(currentVisitLink)){
				currentSeason.getVisitLinks().add(currentVisitLink);
				app.getDataBase().doAction(new ActionOnDataBase(ACTION.INSERT_VISIT_LINK, currentVisitLink));
				app.startFetchingVsitiLink(currentVisitLink);
			}
		}
		if(state == STATE_BROWSER.PAGE_ERROR){
			String http = getResources().getString(R.string.http);
			String query = url.replace(http, "");
			query = query.replace("/", "");
			fetchData(query);
		}
	}
	@Override
	public void sectionSelected(String section) {
		currentVisitLink.getSectionsSelected().add(section);
		app.getDataBase().doAction(new ActionOnDataBase(ACTION.UPDATE_VISIT_LINK, currentVisitLink));
	}
	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		categoriesFiltersView.setEnabled(enabled);
		filtersView.setEnabled(enabled);
		resultsView.setEnabled(enabled);
		logo.setEnabled(enabled);
	}
	

}
